package com.itheima.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis配置类
 */

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    //自定义RedisTemplate对象交给Spring容器管理代替Spring容器默认引入的对象,修改序列化器,让key不再乱码
    /*
        默认的Key序列化器为：JdkSerializationRedisSerializer ,导致存进Redis的key值前面多了很多乱码,通过在@Configuration配置类中自定义RedisTemplate对象交给Spring容器管理代替Spring默认引入的对象,修改序列化器为StringRedisSerializer,让key不再乱码便于查看

        而value依然有乱码,因为使用的也是JdkSerializationRedisSerializer序列化器,但不必修改,因为SpringDataRedis框架存取时自动序列化反序列化,所以程序中取数据时不会乱码
         */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {

        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();

        //默认的Key序列化器为：JdkSerializationRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setConnectionFactory(connectionFactory);

        return redisTemplate;
    }

}
